package lock;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author jiangwz
 * @create 2019/7/10.
 */
public class Container02 {

    // 仓库容量
    private final int MAX_SIZE = 10;
    // 仓库存储的载体
    private LinkedList<Object> list = new LinkedList<>();

    private ReentrantLock lock = new ReentrantLock();

    private Condition producer = lock.newCondition();
    private Condition consumer = lock.newCondition();

    public void put(Object o){
        lock.lock();
        try {
            while (list.size() >= MAX_SIZE) {
                try {
                    producer.await();
                } catch (InterruptedException e) {
                }
            }
            list.add(o);
            System.out.println(Thread.currentThread().getName() + " put当前容器里有"+ list.size() + "个对象");
            consumer.signalAll();
        }catch(Exception e){}finally {
            lock.unlock();
        }
    }

    public void get() throws InterruptedException {
        lock.lock();
        try {
            while (list.size() == 0) {
                consumer.await();
            }
            Object o = list.removeFirst();
            System.out.println(Thread.currentThread().getName() + " get当前容器里有"+ list.size() + "个对象");
            producer.signalAll();
        }finally {
            lock.unlock();
        }
    };

    public static void main(String[] args){
        Container02 c = new Container02();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                try {
                    while (true){
                        c.get();
                    }
                } catch (InterruptedException e) {}
            },"c").start();
        }
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < 2; i++) {
            new Thread(()-> {
                for (int j = 0; j < 25; j++) {
                    c.put(j);
                }
            },"p").start();
        }
    }

}
